import Vue from 'vue'
import App from './App'

import router from './router'
import axios from 'axios'
import { Message,Loading,DatePicker,TimePicker,Input,Select,Button,Option,pagination,cascader,MessageBox,RadioGroup,Radio} from 'element-ui'
Vue.use(Input)
Vue.use(Option)
Vue.use(Select)
Vue.use(DatePicker)
Vue.use(TimePicker)
Vue.use(pagination)
Vue.use(cascader)
Vue.use(RadioGroup)
Vue.use(Radio)
Vue.use(Button)

// axios.defaults.baseURL = 'https://api.huoxingy.com/v1/inv';
// 

// 根据环境来选择api地址
let baseUrl = window.location.hostname;
console.log(baseUrl)
switch (baseUrl) {
    case "localhost":
        axios.defaults.baseURL = 'https://staging-api.huoxingy.com/v1/inv';
        break;
    case "staging-inventory.huoxingy.com":
        axios.defaults.baseURL = 'https://staging-api.huoxingy.com/v1/inv';
        break;
    case "prod-test-inventory.huoxingy.com":
        axios.defaults.baseURL = 'https://prod-test-api.huoxingy.com/v1/inv';
        break;
    default:
        axios.defaults.baseURL = 'https://prod-api.huoxingy.com/v1/inv';
        break;
}
// 

// 
// axios.defaults.baseURL = 'http://192.168.0.108:9090/v1/inv/';
axios.defaults.headers.post['Content-Type'] = 'application/json';

/*
    设置请求拦截器
*/
axios.interceptors.request.use(function(config) {
    let token = sessionStorage.getItem('token');
    if (token) {
        config.headers.Authorization = token;
    }
    return config;
}, function(error) {
    return Promise.reject(error);
});

/*
    添加响应拦截器
*/
axios.interceptors.response.use(function(response) {
    return response;
}, function(error) {
    if (error.response) {
        let tipText;
        error.response.data.message?tipText=error.response.data.message:tipText=error.response.data;
        if ( error.response.status == 401 ) {
            window.location.href = window.location.href.split('#')[0]+'#/login';
            tipText = '帐号失效，请重新登录';
        } else if ( error.response.status == 403 ) {
            // window.location.href = window.location.href.split('#')[0]+'#/login';
            tipText = '权限不足';
        }
        Message.error({
            message: tipText,
        })
    }
    return Promise.reject(error);
});


/*
    添加自定义过滤器
*/
Vue.filter('numberToDate', function ( val ) {
    let dateStr = new Date(val).toLocaleDateString();
    return dateStr;
})

Vue.filter('numberToTime', function ( val ) {
    let date = new Date(val);
    let dateStr = (date.getHours()<10?'0'+date.getHours():date.getHours()) + ':' + (date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes());
    return dateStr;
})

Vue.filter('numberToAllDate', function ( val ) {
    if ( !val ) {
        return '';
    }
    let date = new Date(val);
    let dateStr =date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate()+'-'+ (date.getHours()<10?'0'+date.getHours():date.getHours()) + ':' + (date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes())+ ':' + (date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds());
    return dateStr;
})
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
Vue.prototype.$posPrint = function ( num, str ) {
    window.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
    prn1_print( num );

    // 直接打印
    function prn1_print( num ) {
        CreateOneFormPage();
        window.LODOP.SET_PRINT_COPIES(num);
        window.LODOP.PRINT();
    }; 
    function CreateOneFormPage() {
        window.LODOP = getLodop();
        window.LODOP.PRINT_INIT("pos小票打印");
        window.LODOP.SET_PRINT_PAGESIZE(3, '58mm', 100, 4);
        window.LODOP.ADD_PRINT_HTM(0, "1mm","RightMargin:1mm","BottomMargin:5mm", str);
    };
}
Vue.prototype.$uuid = function ( len, radix ) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
        // rfc4122, version 4 form
        var r;
 
        // rfc4122 requires these characters
        // uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
 
        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for ( i = 0; i < 32; i++ ) {
            if ( !uuid[i] ) {
                r = 0 | Math.random()*62;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}

let dateRange = {
    currentDate: new Date(),
    millisecond: 1000 * 60 * 60 * 24,//一天的毫秒数
    getThisWeek: function() {
        //起止日期数组
        var startStop = new Array();
        //返回date是一周中的某一天
        var week = dateRange.currentDate.getDay();
        //减去的天数
        var minusDay = week != 0 ? week - 1 : 6;
        //本周 周一
        var monday = new Date(dateRange.currentDate.getTime() - (minusDay * 
 
 dateRange.millisecond));
        //本周 周日
        var sunday = new Date(monday.getTime() + (6 * dateRange.millisecond));
        //添加本周时间
        startStop.push(dateRange.formatterDate(monday)); //本周起始时间
        //添加本周最后一天时间
        startStop.push(dateRange.formatterDate(sunday)); //本周终止时间
        //返回
        return startStop;
    },
    /**
     * 获得上一周的起止日期
     */
    getLastWeek: function() {
        //起止日期数组
        var startStop = new Array();
        //返回date是一周中的某一天
        var week = dateRange.currentDate.getDay();
        //减去的天数
        var minusDay = week != 0 ? week - 1 : 6;
        //获得当前周的第一天
        var currentWeekDayOne = new Date(dateRange.currentDate.getTime() - 
 
 (dateRange.millisecond * minusDay));
        //上周最后一天即本周开始的前一天
        var priorWeekLastDay = new Date(currentWeekDayOne.getTime() - 
 
 dateRange.millisecond);
        //上周的第一天
        var priorWeekFirstDay = new Date(priorWeekLastDay.getTime() - (dateRange.millisecond 
 
 * 6));
 
        startStop.push(dateRange.formatterDate(priorWeekFirstDay));
        startStop.push(dateRange.formatterDate(priorWeekLastDay));
        //返回
        return startStop;
    },
    /**
     * 获得这个月的起止日期
     */
    getThisMonth: function() {
        var startStop = new Array();
        //获得当前月份0-11
        var currentMonth = dateRange.currentDate.getMonth();
        //获得当前年份4位年
        var currentYear = dateRange.currentDate.getFullYear();
        //求出本月第一天
        var firstDay = new Date(currentYear, currentMonth, 1);
        //当为12月的时候年份需要加1
        //月份需要更新为0 也就是下一年的第一个月
        //否则只是月份增加,以便求的下一月的第一天
        if (currentMonth == 11) {
            currentYear++;
            currentMonth = 0;
        } else {
            currentMonth++;
        }
        //下月的第一天
        var nextMonthDayOne = new Date(currentYear, currentMonth, 1);
        //求出上月的最后一天
        var lastDay = new Date(nextMonthDayOne.getTime() - dateRange.millisecond);
 
        startStop.push(dateRange.formatterDate(firstDay));
        startStop.push(dateRange.formatterDate(lastDay));
        //返回
        return startStop;
    },
    /**
     * 获得上个月的起止日期
     */
    getLastMonth: function() {
        var startStop = new Array();
        //获得当前月份0-11
        var currentMonth = dateRange.currentDate.getMonth();
        //获得当前年份4位年
        var currentYear = dateRange.currentDate.getFullYear();
        var currentDay = new Date(currentYear, currentMonth, 1);
        //上个月的第一天
        //年份为0代表,是本年的第一月,所以不能减
        if (currentMonth == 0) {
            currentMonth = 11; //月份为上年的最后月份
            currentYear--; //年份减1
        }
        else {
            currentMonth--;
        }
        var firstDay =  new Date(currentYear, currentMonth, 1);
        //求出上月的最后一天
        var lastDay = new Date(currentDay.getTime() - dateRange.millisecond);
 
        startStop.push(dateRange.formatterDate(firstDay));
        startStop.push(dateRange.formatterDate(lastDay));
        //返回
        return startStop;
    },
    /**
     * 格式化日期（不含时间）
     */
    formatterDate : function(date) {
        var datetime = date.getFullYear()
            + "/"// "年"
            + ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0"
            + (date.getMonth() + 1))
            + "/"// "月"
            + (date.getDate() < 10 ? "0" + date.getDate() : date
                .getDate());
        return datetime;
    }
 }
 
 Vue.prototype.$dateRange = dateRange

Vue.prototype.$http = axios;


Vue.use(Loading.directive)
Vue.prototype.$loading = Loading.service
Vue.prototype.$message = Message
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$confirm = MessageBox.confirm;
Vue.config.productionTip = false


Vue.directive('focus', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: function (el) {
        // 聚焦元素
        el.focus();
    }
})



/* eslint-disable no-new */
new Vue({
  	el: '#app',
  	router,
  	template: '<App/>',
  	components: { App }
})
